package com.ydkj.a37e_mall.Resource.Utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.widget.Toast;

import com.ydkj.a37e_mall.R;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;


/**
 * 常用工具类
 *
 * @author Administrator
 */
@SuppressLint("SimpleDateFormat")
public class CommonUtil {

    public final static File sdcardFile = Environment
            .getExternalStorageDirectory();

    /**
     * 判断是否有SDCARD
     *
     * @return
     */
    public static boolean isSDcardExist() {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean toRoundCorner(Context context) {
        ConnectivityManager connManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mWifi = connManager
                .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        return mWifi.isConnected();
    }

    /**
     * 是否有可用网络
     *
     * @param context
     * @return
     */
    public static boolean isNetworkConnected(Context context) {
        ConnectivityManager manager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (manager == null) {
            return false;
        }
        NetworkInfo info = manager.getActiveNetworkInfo();
        if (info == null) {
            return false;
        }
        TelephonyManager tm = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        if (tm == null) {
            return false;
        }
        if ((tm.getDataState() == TelephonyManager.DATA_CONNECTED || tm
                .getDataState() == TelephonyManager.DATA_ACTIVITY_NONE)
                && info.isAvailable()) {
            return true;
        } else {
            return false;
        }
    }

    public static void showToast(Context mContext, int resId) {
        Toast.makeText(mContext, resId, Toast.LENGTH_SHORT).show();
    }

    public static void showToast(Context mContext, String text) {
        Toast.makeText(mContext, text, Toast.LENGTH_SHORT).show();
    }

    public static String getImsi(Context mContext) {
        TelephonyManager mTelephonyMgr = (TelephonyManager) mContext
                .getSystemService(Context.TELEPHONY_SERVICE);
        return mTelephonyMgr.getSubscriberId();
    }

    public static String getImei(Context mContext) {
        TelephonyManager mTelephonyMgr = (TelephonyManager) mContext
                .getSystemService(Context.TELEPHONY_SERVICE);
        return mTelephonyMgr.getDeviceId();
    }

    public static boolean isWifiConnect(Context context) {
        ConnectivityManager connManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mWifi = connManager
                .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        return mWifi.isConnected();
    }

    public static String createRandom(boolean numberFlag, int length){
        String retStr = "";
        String strTable = numberFlag ? "1234567890" : "1234567890abcdefghijkmnpqrstuvwxyz";
        int len = strTable.length();
        boolean bDone = true;
        do {
            retStr = "";
            int count = 0;
            for (int i = 0; i < length; i++) {
                double dblR = Math.random() * len;
                int intR = (int) Math.floor(dblR);
                char c = strTable.charAt(intR);
                if (('0' <= c) && (c <= '9')) {
                    count++;
                }
                retStr += strTable.charAt(intR);
            }
            if (count >= 2) {
                bDone = false;
            }
        } while (bDone);

        return retStr;
    }

    public static String getMD5(String string) {
        if (string == null || string.trim().length() < 1) {
            return null;
        }
        try {
            return getMD5(string.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    private static String getMD5(byte[] source) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            StringBuffer result = new StringBuffer();
            for (byte b : md5.digest(source)) {
                result.append(Integer.toHexString((b & 0xf0) >>> 4));
                result.append(Integer.toHexString(b & 0x0f));
            }
            return result.toString();
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    public static String getTimeString() {
        return getTimeString("yyyyMMddHHmmss");
    }

    public static String getDayString() {
        return getTimeString("yyyyMMdd");
    }

    public static String getTimeString(String pattern) {
        return new SimpleDateFormat(pattern).format(new Date());
    }

    public static String getWeek(String time) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        Date date = null;
        try {
            date = dateFormat.parse(time);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        SimpleDateFormat dateFm = new SimpleDateFormat("EEEE");
        return dateFm.format(date);
    }

    public static String getTimeString(long time) {
        return getTimeString("yyyyMMddHHmmss");
    }

    public static String getTimeString(String pattern, long time) {
        return new SimpleDateFormat(pattern).format(new Date(time));
    }

    /**
     * 获取当前应用的名称
     *
     * @param context
     * @return
     */
    public static String getSimplePackageName(Context context) {
        return context.getPackageName().substring(
                context.getPackageName().lastIndexOf(".") + 1);
    }

    public static String getImagePath(Context context) {
        StringBuilder sb = new StringBuilder();
        sb.append(sdcardFile);
        sb.append(File.separator);
        sb.append(getSimplePackageName(context));
        sb.append(File.separator);
        sb.append(AppContants.IMAGE);
        return sb.toString();
    }

    public static void createFileDirs(String filePath) {
        StringTokenizer st = new StringTokenizer(filePath, File.separator);
        String path1 = st.nextToken() + File.separator;
        String path2 = path1;
        while (st.hasMoreTokens()) {
            path1 = st.nextToken() + File.separator;
            path2 += path1;
            File inbox = new File(path2);
            if (!inbox.exists())
                inbox.mkdir();
        }
    }

    /**
     * 等比例缩放图片（带滤波器�?
     *
     * @param srcFile   来源文件
     * @param dstFile   目标文件
     * @param dstMaxWH  目标文件宽高
     * @param bContrast 提高对比度滤波器，可使图片变亮丽
     */
    public static boolean scaleImageWithFilter(File srcFile, File dstFile,
                                               int dstMaxWH, Boolean bContrast) {
        boolean bRet = false;
        // 路径文件不存�??
        if (!srcFile.exists()) {
            return bRet;
        }
        try {
            // 打开源文�??
            Bitmap srcBitmap;
            {
                java.io.InputStream is;
                is = new FileInputStream(srcFile);
                Options opts = getOptionsWithInSampleSize(
                        srcFile.getPath(), dstMaxWH);
                srcBitmap = BitmapFactory.decodeStream(is, null, opts);
                if (srcBitmap == null)
                    return bRet;
            }
            // 原图片宽�??
            int width = srcBitmap.getWidth();
            int height = srcBitmap.getHeight();
            // 获得缩放因子
            float scale = 1.f;
            {
                if (width > dstMaxWH || height > dstMaxWH) {
                    float scaleTemp = (float) dstMaxWH / (float) width;
                    float scaleTemp2 = (float) dstMaxWH / (float) height;
                    if (scaleTemp > scaleTemp2)
                        scale = scaleTemp2;
                    else
                        scale = scaleTemp;
                }
            }
            // 图片缩放
            Bitmap dstBitmap;
            if (scale == 1.f)
                dstBitmap = srcBitmap;
            else {
                Matrix matrix = new Matrix();
                matrix.postScale(scale, scale);
                dstBitmap = Bitmap.createBitmap(srcBitmap, 0, 0, width, height,
                        matrix, true);
                if (!srcBitmap.isRecycled())
                    srcBitmap.recycle();
                srcBitmap = null;
            }
            // 提高对比�??
            if (bContrast) {
                Bitmap tempBitmap = Bitmap.createBitmap(dstBitmap.getWidth(),
                        dstBitmap.getHeight(), Config.ARGB_8888);
                Canvas canvas = new Canvas(tempBitmap);
                ColorMatrix cm = new ColorMatrix();
                float contrast = 30.f / 180.f; // 提高30对比�??
                setContrast(cm, contrast);
                Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
                paint.setColorFilter(new ColorMatrixColorFilter(cm));
                canvas.drawBitmap(dstBitmap, 0, 0, paint);
                if (!dstBitmap.isRecycled())
                    dstBitmap.recycle();
                dstBitmap = null;
                dstBitmap = tempBitmap;
            }
            // 保存文件
            if (dstFile.exists())
                dstFile.delete();
            BufferedOutputStream bos = new BufferedOutputStream(
                    new FileOutputStream(dstFile));
            dstBitmap.compress(CompressFormat.JPEG, 90, bos);
            if (!dstBitmap.isRecycled())
                dstBitmap.recycle();
            dstBitmap = null;
            bos.flush();
            bos.close();
            bRet = true;
        } catch (Exception e) {
            return bRet;
        }
        return bRet;
    }

    /**
     * 获取长宽都不超过160dip的图片，基本思想是设置Options.inSampleSize按比例取得缩略图
     */
    public static Options getOptionsWithInSampleSize(String filePath,
                                                     int maxWidth) {
        Options bitmapOptions = new Options();
        bitmapOptions.inJustDecodeBounds = true;// 只取得outHeight(图片原始高度)�??
        // outWidth(图片的原始宽�??而不加载图片
        BitmapFactory.decodeFile(filePath, bitmapOptions);
        bitmapOptions.inJustDecodeBounds = false;
        int inSampleSize = bitmapOptions.outWidth / (maxWidth / 10);// 应该直接�??60的，但这里出16是为了增加一位数的精�??
        if (inSampleSize % 10 != 0) {
            inSampleSize += 10;// 尽量取大点图片，否则会模�??
        }
        inSampleSize = inSampleSize / 10;
        if (inSampleSize <= 0) {// 判断200是否超过原始图片高度
            inSampleSize = 1;// 如果超过，则不进行缩�??
        }
        bitmapOptions.inSampleSize = inSampleSize;
        return bitmapOptions;
    }

    /**
     * 设置对比度矩�?
     */
    private static void setContrast(ColorMatrix cm, float contrast) {
        float scale = contrast + 1.f;
        float translate = (-.5f * scale + .5f) * 255.f;
        cm.set(new float[]{scale, 0, 0, 0, translate, 0, scale, 0, 0,
                translate, 0, 0, scale, 0, translate, 0, 0, 0, 1, 0});
    }

    /**
     * 是否要缩放图�?
     * <p>
     * 1.图片尺寸大于200k 2.图片大小大于屏幕尺寸
     */
    public static Boolean isNeedScaleImage(String filename) {
        // 判断文件大小
        File imageFile = new File(filename);
        if (!imageFile.exists()) {
            return false;
        }
        if (imageFile.length() > AppContants.MAX_SIZE_IMAGE) {
            return true;
        }
        // 判断文件尺寸
        Options bitmapOptions = new Options();
        bitmapOptions.inJustDecodeBounds = true;// 只取得outHeight(图片原始高度)�??
        bitmapOptions.inSampleSize = 1;
        // outWidth(图片的原始宽�??而不加载图片
        Bitmap bitmap = BitmapFactory.decodeFile(filename, bitmapOptions);
        if (bitmap == null) {
            return false;
        }
        return false;
    }

    public static int getScreenMin(Context context) {
        DisplayMetrics dm = new DisplayMetrics();
        dm = context.getResources().getDisplayMetrics();
        int screenWidth = dm.widthPixels;
        int screenHeight = dm.heightPixels;
        return (screenWidth > screenHeight) ? screenHeight : screenWidth;
    }

    /**
     * 获取log文件夹路径，包含sdcard路径
     *
     * @param context
     * @return
     */
    public static String getLogPath(Context context) {
        StringBuilder sb = new StringBuilder();
        sb.append(sdcardFile);
        sb.append(File.separator);
        sb.append(getSimplePackageName(context));
        sb.append(File.separator);
        sb.append(AppContants.LOG);
        return sb.toString();
    }

    public static boolean isEmpty(String str) {
        if (str == null || str.trim().equals("")) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 打开设置网络界面
     */
    public static void setNetworkMethod(final Context context) {
        // 提示对话框
        Builder builder = new Builder(context);
        builder.setTitle(R.string.network_set_tip)
                .setMessage(R.string.network_set_confirm)
                .setPositiveButton(R.string.set,
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                // TODO Auto-generated method stub
                                Intent intent = null;
                                // 判断手机系统的版本即API大于10 就是3.0或以上版本
                                if (android.os.Build.VERSION.SDK_INT > 10) {
                                    intent = new Intent(
                                            android.provider.Settings.ACTION_WIRELESS_SETTINGS);
                                } else {
                                    intent = new Intent();
                                    ComponentName component = new ComponentName(
                                            "com.android.settings",
                                            "com.android.settings.WirelessSettings");
                                    intent.setComponent(component);
                                    intent.setAction("android.intent.action.VIEW");
                                }
                                context.startActivity(intent);
                            }
                        })
                .setNegativeButton(R.string.common_cancel,
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                // TODO Auto-generated method stub
                                dialog.dismiss();
                            }
                        }).show();
    }

    /**
     * 获取手机号码
     */
    public static String getPhoneNum(Context context) {
        String phoneNum = "";
        TelephonyManager telephonyManager = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        phoneNum = telephonyManager.getLine1Number();
        return phoneNum;
    }

    /**
     * 校验码
     *
     * @param params
     * @return
     */
    public static String checkSum(Object... params) {
        try {
            String checkSum = "";
            for (Object obj : params) {
                checkSum = checkSum + obj.toString();
            }
            checkSum = checkSum + Const.APPSECRET;
            checkSum = getMD5(checkSum);
            return checkSum;
            // byte[] bytes = checkSum.getBytes(Const.ENCODE);
            // return NativeEncrypt.getInstance()
            // .encryptBytes(bytes, bytes.length).toLowerCase();
        } catch (Exception e) {
            // TODO: handle exception
        }
        return "";
    }

    /**
     * 获取版本号
     */
    public static String getCurrentVersion(Context context) {
        String version = "";
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            version = pi.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return version;
    }

    /**
     * 将图片转换成圆角图片
     *
     * @param bitmap
     * @param pixels
     * @return
     */
    public static Bitmap toRoundCorner(Bitmap bitmap, int pixels) {
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
                bitmap.getHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);
        final float roundPx = pixels;
        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        //
        // ColorMatrix cm = new ColorMatrix();
        // float contrast = 30.f / 180.f; // 提高30对比率
        // setContrast(cm, contrast);
        // paint.setColorFilter(new ColorMatrixColorFilter(cm));
        canvas.drawBitmap(bitmap, rect, rect, paint);
        return output;
    }

    public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float ratio) {

        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
                bitmap.getHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        canvas.drawRoundRect(rectF, bitmap.getWidth() / ratio,
                bitmap.getHeight() / ratio, paint);

        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);
        return output;
    }

    /**
     * 保存图片到项目文件中路径/sdcard/marry/image/md5(url).jpg
     *
     * @param bitmap
     */
    public static void storeInSD(Bitmap bitmap, String url, String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdir();
        }
        File imageFile = new File(file, getMD5(url) + ".jpg");
        try {
            imageFile.createNewFile();
            FileOutputStream fos = new FileOutputStream(imageFile);
            bitmap.compress(CompressFormat.JPEG, 50, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 获取项目中的图片
     *
     * @param url
     * @param filePath
     * @return
     */
    public static Bitmap getBitmap(String url, String filePath) {
        File imageFile = new File(filePath, getMD5(url) + ".jpg");
        Bitmap bitmap = null;
        if (imageFile.exists()) {
            try {
                bitmap = BitmapFactory.decodeStream(new FileInputStream(
                        imageFile));
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return bitmap;
    }

    //将bitmap转为路径地址
    public static String getBitmapToPaths(Activity activity, Bitmap bitmap) {
        Uri uri = Uri.parse(MediaStore.Images.Media.insertImage(activity.getContentResolver(), bitmap, null, null));
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = activity.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    public static String listToString(List list, char separator) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            sb.append(list.get(i)).append(separator);
        }
        return sb.toString().substring(0, sb.toString().length() - 1);
    }

    public static Double roundDouble(double dou, int i) {
        Double d = null;
        try {
            double factor = Math.pow(10, i);
            d = Math.floor(dou * factor + 0.5) / factor;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return d;
    }

    //JSON格式化方法
    public static String format(String jsonStr) {
        int level = 0;
        StringBuffer jsonForMatStr = new StringBuffer();
        for(int i=0;i<jsonStr.length();i++){
            char c = jsonStr.charAt(i);
            if(level>0&&'\n'==jsonForMatStr.charAt(jsonForMatStr.length()-1)){
                jsonForMatStr.append(getLevelStr(level));
            }
            switch (c) {
                case '{':
                case '[':
                    jsonForMatStr.append(c+"\n");
                    level++;
                    break;
                case ',':
                    jsonForMatStr.append(c+"\n");
                    break;
                case '}':
                case ']':
                    jsonForMatStr.append("\n");
                    level--;
                    jsonForMatStr.append(getLevelStr(level));
                    jsonForMatStr.append(c);
                    break;
                default:
                    jsonForMatStr.append(c);
                    break;
            }
        }

        return jsonForMatStr.toString();

    }

    private static String getLevelStr(int level){
        StringBuffer levelStr = new StringBuffer();
        for(int levelI = 0;levelI<level ; levelI++){
            levelStr.append("\t");
        }
        return levelStr.toString();
    }
    //判断String是不是数字
    public static boolean isNumeric00(String str) {
        try {
            Double.parseDouble(str);
            return true;
        } catch (NumberFormatException e) {
            System.out.println("异常：\"" + str + "\"不是数字/整数...");
            return false;
        }
    }
}
